<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Schedule extends BaseController {

	public function __construct() {
        parent::__construct();
        // 后台初始化方法
        $this->admin_init();
        // 检查用户身份
        if($this->userType != USER_TYPE_SCHOOL && $this->userType != USER_TYPE_TEACHER) redirect(admin_url("login"));
        // 加载类库
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        $this->load->model('contentModel');
        $this->load->model('dataModel');
    }
    
    // 编辑课程模板页面
    public function save_schedule() {
        $id = $this->get('id');
        // 如传id，就是更新操作
        if(!empty($id)) {
            $this->scheduleId = $id;
            $this->schedule = $this->classesModel->get_school_schedule_info($id);
            // 获取上课数据数组
            $timeArr = json_decode($this->schedule['schedule_time_json'], true);
            if(!empty($timeArr)) {
                foreach($timeArr as $key => $time) {
                    // 计算课程结束时间
                    $timeArr[$key]['endTime'] = add_time($time['beginTime'], $time['duration']);
                    // 计算考勤开始时间
                    $signInterval = isset($time['sign_interval']) ? $time['sign_interval'] : 10;
                    $timeArr[$key]['sign_interval'] = $signInterval;
                    $timeArr[$key]['signBeginTime'] = subtract_time($time['beginTime'], $signInterval);
                    $timeArr[$key]['signEndTime'] = $time['beginTime'];
                    $timeArr[$key]['refresh'] = isset($time['refresh']) ? $time['refresh'] : '否';
                }

                $this->schedule['timeArr'] = $timeArr;
            }
        }

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "save_schedule");
    }

    // 编辑课程模板页面
    public function save_schedule2() {
        $id = $this->get('id');
        // 如传id，就是更新操作
        if(!empty($id)) {
            $this->scheduleId = $id;
            $this->schedule = $this->classesModel->get_school_schedule_info($id);
            // 获取上课数据数组
            $timeArr = json_decode($this->schedule['schedule_time_json'], true);
            if(!empty($timeArr)) {
                // 计算课程结束时间
                foreach($timeArr as $key => $time) {
                    $timeArr[$key]['endTime'] = add_time($time['beginTime'], $time['duration']);
                    // 判断是否
                }
                $this->schedule['timeArr'] = $timeArr;
            }
        }

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "save_schedule2");
    }

    // 保存课程模板
    public function save_schedule_action2() {
        $id = $this->post('id');
        $title = $this->post('title');
        $weekDays = $this->post('week_days');
        $startStr = $this->post('start');
        $endStr = $this->post('end');
        $startArr = explode(',', $startStr);
        $endArr = explode(',', $endStr);
        // 上课时间数组
        $timeArr = array();
        // 上午节数
        $morningNum = 0;
        // 下午节数
        $afternoonNum = 0;
        foreach($startArr as $key => $start) {
            if($start == $endArr[$key]) {
                $key ++;
                throw new Exception('第' . $key . '节：开始时间等于结束时间');
            }
            if($start > $endArr[$key]) {
                $key ++;
                throw new Exception('第' . $key . '节：开始时间大于结束时间');
            }
            $timeArr[$key]['timeslotInDay'] = $key + 1;
            $timeArr[$key]['beginTime'] = $start;
            $timeArr[$key]['duration'] = get_duration($start, $endArr[$key]);
            if($key + 1 === count($startArr)) {
                $timeArr[$key]['breakDuration'] = 10;
            } else {
                if($endArr[$key] > $startArr[$key + 1]) {
                    $next = $key + 2;
                    throw new Exception('第' . $next . '节不能比上一节时间小');
                }
                $timeArr[$key]['breakDuration'] = get_duration($endArr[$key], $startArr[$key + 1]);
            }
            // 
            // 判断是否上午
            $startHour = explode(':', $start)[0];
            if($startHour <= 12) {
                $morningNum ++;
            }
        }
        // 计算下午节数
        $afternoonNum = count($startArr) - $morningNum;
        $timeJson = json_encode($timeArr, JSON_UNESCAPED_UNICODE);
        $data = array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            // 暂不区分年级
            'grade_id' => 0,
            'schedule_title' => $title,
            // 现在只使用本周课程数据
            'schedule_this_week' => 1,
            'schedule_week_days' => $weekDays,
            'schedule_morning_number' => $morningNum,
            'schedule_afternoon_number' => $afternoonNum,
            'schedule_time_json' => $timeJson,
            'updatetime' => date('Y-m-d H:i:s')
        );
        if(empty($id)) {
            // 新增
            $this->db->insert(ClassesModel::$scheduleTable, array_merge($data,array('createtime' => date('Y-m-d H:i:s'))));
            $msg = '添加成功';
        } else {
            // 更新
            $this->db->where('id', $id);
            $this->db->update(ClassesModel::$scheduleTable, $data);
            $msg = '修改成功';
        }
        exit(json($msg, true));
    }
    // 保存课程模板
    public function save_schedule_action() {
        $id = $this->post('id');
        $title = $this->post('title');
        $weekDays = $this->post('week_days');
        $scheduleDataArr = $this->post('time_arr');
        $gradeId = $this->post('grade_id') ? $this->post('grade_id') : 0;
        // 上课时间数组
        $timeArr = array();
        // 上午节数
        $morningNum = 0;
        // 下午节数
        $afternoonNum = 0;
        if(empty($scheduleDataArr)) {
            throw new Exception('课表不能为空');
        }
        foreach($scheduleDataArr as $key => $scheduleData) {
            if($scheduleData['begin_time'] == $scheduleData['end_time']) {
                throw new Exception('第' . $scheduleData['timeslot'] . '节：开始时间等于结束时间');
            }
            if($scheduleData['begin_time'] > $scheduleData['end_time']) {
                throw new Exception('第' . $scheduleData['timeslot'] . '节：开始时间大于结束时间');
            }
            $timeArr[$key]['sign_interval'] = $scheduleData['sign_interval'];
            $timeArr[$key]['refresh'] = $scheduleData['refresh'];
            $timeArr[$key]['timeslotInDay'] = $scheduleData['timeslot'];
            $timeArr[$key]['beginTime'] = $scheduleData['begin_time'];
            $timeArr[$key]['duration'] = get_duration($scheduleData['begin_time'], $scheduleData['end_time']);
            // 处理interval设置过大情况
            if($scheduleData['sign_interval'] > 10) {
                $minCount = explode(':', $scheduleData['begin_time'])[0] * 60 + explode(':', $scheduleData['begin_time'])[1];
                if($scheduleData['sign_interval'] > $minCount) {
                    $timeArr[$key]['sign_interval'] = $minCount;
                }
            }

            if($key + 1 === count($scheduleDataArr)) {
                $timeArr[$key]['breakDuration'] = 10;
            } else {
                if($scheduleDataArr[$key + 1]['begin_time'] < $scheduleData['end_time']) {
                    $num = $key + 2;
                    throw new Exception('第' . $num . '节上课时间不能比上一节时间小');
                }
                $timeArr[$key]['breakDuration'] = get_duration($scheduleData['end_time'], $scheduleDataArr[$key + 1]['begin_time']);
                // 限制考勤时间不能大于上节课结束时间
                if(date('H:i', strtotime($scheduleDataArr[$key + 1]['begin_time']) - $scheduleDataArr[$key + 1]['sign_interval'] * 60)  < $scheduleData['end_time']) {
                    throw new Exception('第' .  ++$scheduleData['timeslot'] . '节：考勤时间不能比上一节时间小');
                }
            }
            // 判断是否上午
            $startHour = explode(':', $scheduleData['begin_time'])[0];
            if($startHour <= 12) {
                $morningNum ++;
            }
        }

        // 计算下午节数
        $afternoonNum = count($scheduleDataArr) - $morningNum;
        $timeJson = json_encode($timeArr, JSON_UNESCAPED_UNICODE);
        $data = array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            // // 暂不区分年级
            // 'grade_id' => 0,
            'grade_id' => $gradeId,
            'schedule_title' => $title,
            // 现在只使用本周课程数据
            'schedule_this_week' => 1,
            'schedule_week_days' => $weekDays,
            'schedule_morning_number' => $morningNum,
            'schedule_afternoon_number' => $afternoonNum,
            'schedule_time_json' => $timeJson,
            'updatetime' => date('Y-m-d H:i:s')
        );

        // 兼容身份证
        // // 同步学校：上下午节数不改变
        // if($this->rmxSchool['school_from']) {
        //     unset($data['schedule_morning_number']);
        //     unset($data['schedule_afternoon_number']);
        // }

        if(empty($id)) {
            // 新增
            $this->db->insert(ClassesModel::$scheduleTable, array_merge($data,array('createtime' => date('Y-m-d H:i:s'))));
            $msg = '添加成功';
        } else {
            // 更新
            $this->db->where('id', $id);
            $this->db->update(ClassesModel::$scheduleTable, $data);
            $msg = '修改成功';
        }
        if($gradeId == 0) { 
            // 排查保存年级作息
            // 如缩减节数，删除对应的课程
            // 每天上课节数
            $dailyLessonCount = $morningNum + $afternoonNum;
            $scheduleLessonParams['schoolId'] = $this->rmxSchool['id'];
            $scheduleLessonParams['campusId'] = $this->campusInfo['id'];
            $scheduleLessonParams['isDelete'] = 0;
            $scheduleLessonParams['gtClassIndex'] = $dailyLessonCount;
            $delScheduleLessonList = $this->classesModel->get_school_schedule_lesson_fast($scheduleLessonParams);
            if($delScheduleLessonList) {
                foreach($delScheduleLessonList as $item) {
                    $this->db->update(ClassesModel::$scheduleLessonTable, array(
                        'is_delete' => 1,
                        'updatetime' => date('Y-m-d H:i:s')
                    ), "id = {$item['id']}");
                }
            }
        }
        exit(json($msg, true));
    }
    // 编辑课程页面
    public function save_schedule_lesson() {
        $this->load->model('staffModel');
        $scheduleId = $this->get('schedule_id');
        $classId = $this->get('class_id');
        $this->classInfo = $this->classesModel->get_class_info($classId);
        // 获取课程模板
        $schedule = $this->classesModel->get_school_schedule_info($scheduleId);
        // 获取上课数据数组
        $timeArr = json_decode($schedule['schedule_time_json'], true);
        if(!empty($timeArr)) {
            // 计算课程结束时间
            foreach($timeArr as $key => $time) {
                $timeArr[$key]['endTime'] = add_time($time['beginTime'], $time['duration']);
            }
            $schedule['timeArr'] = $timeArr;
            // 获取
        }
        $this->schedule = $schedule;

        // 获取班级课程列表
        $lessonParams['isDelete'] = 0;
        $lessonParams['schoolId'] =  $this->rmxSchool['id'];
        $lessonParams['scheduleId'] = $scheduleId;
        $lessonParams['classId'] = $classId;
        $lessons = $this->classesModel->get_school_schedule_lesson($lessonParams);
        if(!empty($lessons)) {
            foreach($lessons as $key => $lesson) {
                // 如果是行政班，过滤不是在本课室上课的课程
                if($this->classInfo['class_type'] == CLASSES_TYPE_NORMAL) {
                    if($this->classInfo['classroom_id'] != $lesson['schedule_room_id']) {
                        unset($lessons[$key]);
                        continue;
                    }
                }

                // 获取教师名称
                $lessons[$key]['teacher_name'] = '';
                $teacher = $this->schoolModel->get_school_user_info_realname($lesson['schedule_teacher']);
                if($teacher) {
                    $lessons[$key]['teacher_name'] = $teacher['realname'] ? $teacher['realname'] : $teacher['username'];
                }
                // 获取教室名称
                $lessons[$key]['classroom_name'] = '';
                $classroom = $this->classesModel->get_classroom_info($lesson['schedule_room_id'], 1);
                if($classroom && $classroom['is_delete'] == 0) {
                    $lessons[$key]['classroom_name'] = $classroom['classroom_name'];
                }
            }
            $this->lessons = $lessons;
        }
        // 获取所有科目
        $params['isDelete'] = 0;
        $params['schoolId'] = $this->rmxSchool['id'];
        $this->subjects = $this->schoolModel->get_lesson_list($params);

        // 如果是行政班只显示本班课室
        if($this->classInfo['class_type'] == CLASSES_TYPE_NORMAL) {
            $res = $this->classesModel->get_classroom_info($this->classInfo['classroom_id'], 1);
            if($res) {
                $this->classrooms = array($res);
            } else {
                $this->classrooms = array();
            }
            // 获取班级任课老师列表
            $classCoachParams['schoolId'] = $this->rmxSchool['id'];
            $classCoachParams['classId'] = $classId;
            $classCoachParams['coachType'] = COACH_TYPE_TEACHER; 
            $classCoachTeachList = $this->staffModel->get_coach_list($classCoachParams);
            $this->coachList = $classCoachTeachList;
            // echo '<pre>';var_export($classCoachTeachList);exit;
        } else {
            // 获取所有课室
            $params['campusId'] = $this->campusInfo['id'];
            $this->classrooms = $this->classesModel->get_classroom_list($params);
            // 获取所有任课老师列表
            $coachParams['schoolId'] = $this->rmxSchool['id'];
            $coachParams['coachType'] = COACH_TYPE_TEACHER; 
            $coachList = $this->staffModel->get_coach_list($coachParams);

            // 获取所有教师
            $teacherParams['isDelete'] = 0;
            $teacherParams['schoolId'] = $this->rmxSchool['id'];
            $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
            foreach($teacherList as &$teacher) {
                $teacher['teacher_id'] = $teacher['id'];
                $teacher['subject_ids'] = '';
                $subjectIdArr = array();
                foreach($coachList as $coach) {
                    if($coach['teacher_id'] == $teacher['id']) {
                        $idArr = explode(',', $coach['subject_ids']);
                        foreach($idArr as $id) {
                            if(!in_array($id, $subjectIdArr)) {
                                array_push($subjectIdArr, $id);
                            }
                        }
                    }
                }
                $teacher['subject_ids'] = implode(',', $subjectIdArr);
            }

            $this->coachList = $teacherList;
        }
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "save_schedule_lesson");
    }

    // 保存课程
    public function save_schedule_lesson_action() {
        $lessonId = $this->post('lesson_id');
        $scheduleId = $this->post('schedule_id');
        $classId = $this->post('class_id');
        $weekIndex = $this->post('week_index');
        $classIndex = $this->post('class_index');
        $subject = $this->post('subject');
        $teacherId = $this->post('teacher_id') ? $this->post('teacher_id') : 0;
        $classroomId = $this->post('classroom_id');
        // if(empty($teacherId)) {
        //     throw new Exception('任课教师不能为空');
        // }
        if(empty($classroomId)) {
            throw new Exception('上课课室不能为空');
        }
        $classInfo = $this->classesModel->get_class_info($classId);

        if($classInfo['class_type'] == CLASSES_TYPE_NORMAL) {
            if(empty($classInfo['classroom_id'])) {
                throw new Exception('请先设置班级课室');
            }
            if($classInfo['classroom_id'] != $classroomId) {
                throw new Exception('行政班上课课室必须设置为本班课室');
            }
        }
        // 新增走班课程时判断该是否已存在行政班课程
        if($classInfo['class_type'] == CLASSES_TYPE_TEACHING) {
            $lessonExist = $this->classesModel->get_schedule_lesson_info($scheduleId, $weekIndex, $classIndex, $classroomId);
            if(empty($lessonId)) {
                // 新增
                if($lessonExist) {
                    throw new Exception('该课室已存在行政班课程');
                }
            } else {
                // 更新
                if($lessonExist && $lessonId !== $lessonExist['id']) {
                    throw new Exception('该课室已存在行政班课程');
                }
            }
        }

        $data = array(
            'updatetime' => date('Y-m-d H:i:s'),
            'schedule_lesson' => $subject,
            'schedule_teacher' => $teacherId,
            'schedule_room_id' => $classroomId,
        );
        if(empty($lessonId)) {
            // 新增
            $this->db->insert(ClassesModel::$scheduleLessonTable, array_merge(
                $data, array(
                    'school_id' => $this->rmxSchool['id'],
                    'campus_id' => $this->campusInfo['id'],
                    'is_delete' => 0,
                    'createtime' => date('Y-m-d H:i:s'),
                    'schedule_id' => $scheduleId,
                    'class_id' => $classId,
                    'schedule_week_index' => $weekIndex,
                    'schedule_class_index' => $classIndex,
                )
            ));
        } else {
            // 更新
            $this->db->where('id', $lessonId);
            $this->db->update(ClassesModel::$scheduleLessonTable, $data);
        }
        exit(json('保存成功', true));
    }
    // 删除课程
    public function delete_schedule_lesson_action() {
        $lessonId = $this->post('lesson_id');
        $this->db->where('id', $lessonId);
        $this->db->update(ClassesModel::$scheduleLessonTable, array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s'),
        ));
        exit(json('', true));
    }

    // 删除班级课程
    public function delete_class_lessons_action() {
        $scheduleId = $this->post('schedule_id');
        $classId = $this->post('class_id');

        $this->db->where(array(
            'schedule_id' => $scheduleId,
            'class_id' => $classId
        ));
        $this->db->update(ClassesModel::$scheduleLessonTable, array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s'),
        ));
        exit(json('删除成功', true));
    }

    // 导出课表
    public function export(){
        $this->load->model('staffModel');
        // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
        $onlyOneSchedule = $this->classesModel->check_is_only_one_schedule($this->rmxSchool['id'], $this->campusInfo['id']);
        if($onlyOneSchedule) {
            // 获取学校课程模板
            $scheduleParams['schoolId'] = $this->rmxSchool['id'];
            // 课程暂不区分校区
            $scheduleParams['isThisWeek'] = 1;
            $scheduleParams['isDelete'] = 0;
            $schedule = $this->classesModel->get_school_schedule_row($scheduleParams);
        } else {
            // 年级不同作息
            $gradeScheduleParams['schoolId'] = $this->rmxSchool['id'];
            $gradeScheduleParams['campusId'] = $this->campusInfo['id'];
            $gradeScheduleParams['isDelete'] = 0;
            $gradeScheduleList = $this->classesModel->get_school_schedule($gradeScheduleParams);
            $maxGradeSchedule = array();
            if(empty($gradeScheduleList)) {
                throw new Exception('找不到该学校课程模板');
            }
            foreach($gradeScheduleList as $key => $gradeSchedule) {
                // 获取天数最大值，节数最大值
                if($key == 0) {
                    $maxGradeSchedule = $gradeSchedule;
                } else {
                    $timeArr = json_decode($gradeSchedule['schedule_time_json'], true);
                    $maxGradeScheduleTimeArr = json_decode($maxGradeSchedule['schedule_time_json'], true);
                    $maxGradeScheduleCount = count($maxGradeScheduleTimeArr);
                    if($maxGradeScheduleCount < count($timeArr)) {
                        $maxGradeSchedule = $gradeSchedule;
                    }
                }
            }
            $schedule = $maxGradeSchedule;
        }
       
        // echo'<pre>';var_export($maxGradeSchedule);exit;

        if(empty($schedule)) {
            throw new Exception('找不到该学校课程模板');
        }
        // 课程节数
        $timeArr = json_decode($schedule['schedule_time_json'], true);
        if(empty($timeArr)) {
            throw new Exception('找不到课程模板的上课时间');
        }
        $data = array();
        $classParams['schoolId'] = $this->rmxSchool['id'];
        $classParams['campusId'] = $this->campusInfo['id'];
        // 行政班
        $classParams['classType'] = CLASSES_TYPE_NORMAL;
        $classParams['isDelete'] = 0;
        // 按年级排序
        // $classParams['orderBy'] = '`grade_id` ASC, `id` ASC';
        $classes = $this->classesModel->get_class_list($classParams);

        foreach($classes as $key => $class) {
            // 获取年级名称
            $classes[$key]['grade_name'] = '';
            $grade = $this->classesModel->get_grade_info($class['grade_id']);
            if($grade) {
                $classes[$key]['grade_name'] = $grade['grade_name'];
            }
            // 获取班主任
            $classes[$key]['teacher_name'] = '';
            // $teacher = $this->schoolModel->get_school_user_info_realname($class['class_master']);
            $masterCoach = $this->staffModel->get_master_coach_by_class($class['id']);
            if($masterCoach) {
                $teacher = $this->schoolModel->get_school_user_info_realname($masterCoach['teacher_id']);
            } else {
                $teacher = NULL;
            }

            if($teacher) {
                $classes[$key]['teacher_name'] = $teacher['realname'] ? $teacher['realname'] : $teacher['username'];
            }
            // 获取班级课程
            $classes[$key]['lessons'] = array();
            $lessonParams['schoolId'] = $this->rmxSchool['id'];
            $lessonParams['classId'] = $class['id'];
            // $lessonParams['scheduleId'] = $schedule['id'];   // 兼容年级不同作息
            $lessons = $this->classesModel->get_school_schedule_lesson($lessonParams);
            foreach($lessons as $keyLesson => $lesson) {
                //获取任课老师
                $lessons[$keyLesson]['teacher_name'] = '';
                $teacher = $this->schoolModel->get_school_user_info_realname($lesson['schedule_teacher']);
                // 兼容多任课老师
                $teacherIdArr = explode(',', $lesson['schedule_teacher']);
                $teacherNameArr = array();
                if($teacherIdArr) {
                    foreach($teacherIdArr as $teacherId) {
                        $teacher = $this->schoolModel->get_school_user_info_realname($teacherId);
                        if($teacher) {
                            $teacherNameArr[] = $teacher['realname'];
                        }
                    }
                }
                $lessons[$keyLesson]['teacher_name'] = $teacherNameArr ? implode('/', $teacherNameArr) : '';
            }
            if($lessons) {
                $classes[$key]['lessons'] = $lessons;
            }
        }
        // 合并单元位置
        $mergeLocations = array();
		// excel坐标
        $excelSheetArr = excelSheetIndex();
        // 一天课程数
        $scheduleDayNum = $schedule['schedule_morning_number'] + $schedule['schedule_afternoon_number'];
        // 星期项起始横坐标是2
        $weekRowEnd = 2;
        // 星期项起点坐标是D2
        $weekIndexBegin = 'D2:';
        // 星期项列数填充数组
        $weekFillArray = array();
        // 上下午起始横坐标是2
        $dayRowEnd = 2;
        // 上下午起点坐标是D3
        $dayIndexBegin = 'D3:';
        // 上下午列数填充数组
        $dayFillArray = array();
        for($i = 1; $i <= $schedule['schedule_week_days']; $i++) {
            // 合并星期项
            $weekRowEnd = $weekRowEnd + $scheduleDayNum;
            $mergeLocations[] = $weekIndexBegin . $excelSheetArr[$weekRowEnd] . 2;
            // 下一个起点坐标
            $weekIndexBegin = $excelSheetArr[$weekRowEnd + 1] . '2:';
            
            // 判断是否有下午课程
            if($schedule['schedule_morning_number'] > 0) {
                // 合并上午项
                $dayRowEnd = $dayRowEnd + $schedule['schedule_morning_number'];
                $mergeLocations[] = $dayIndexBegin . $excelSheetArr[$dayRowEnd] . 3;
                // 上下午列数填充数组
                array_push($dayFillArray, '上午');
                for($j = 1; $j <= $schedule['schedule_morning_number'] - 1; $j++) {
                    array_push($dayFillArray, '');
                }
                // 下一个起点坐标
                $dayIndexBegin = $excelSheetArr[$dayRowEnd + 1] . '3:';
            }

            // 判断是否有下午课程
            if($schedule['schedule_afternoon_number'] > 0) {
                // 合并下午项
                $dayRowEnd = $dayRowEnd + $schedule['schedule_afternoon_number'];
                $mergeLocations[] = $dayIndexBegin . $excelSheetArr[$dayRowEnd] . 3;
                // 上下午列数填充数组
                array_push($dayFillArray, '下午');
                for($j = 1; $j <= $schedule['schedule_afternoon_number'] - 1; $j++) {
                    array_push($dayFillArray, '');
                }
                // 下一个起点坐标
                $dayIndexBegin = $excelSheetArr[$dayRowEnd + 1] . '3:';
            }
        }
        // 合并年级
        $arr = array();
        if(!empty($classes)) {
            foreach($classes as $class) {
                $gradeId = $class['grade_id'];
                if(isset($arr[$gradeId])) {
                    $arr[$gradeId]++;
                } else {
                    $arr[$gradeId] = 1;
                }
            }
            $begin = 5;
            foreach($arr as $val) {
                $end = $begin + intval($val) * 2 - 1;
                array_push($mergeLocations, 'A' . $begin . ':A' . $end);
                $begin = $end + 1;
            }
        }
        $firstRow = $schedule['schedule_title'] ? $schedule['schedule_title'] : $this->rmxSchool['school_name'] . '总课表';
        $data[0] = array($firstRow);
        $data[1] = array('年级', '班级', '班主任');
        $data[2] = array('年级', '班级', '班主任');
        $data[3] = array('年级', '班级', '班主任');
        // 设置星期项
        $weekDays = array('星期一', '星期二', '星期三', '星期四', '星期五');
        // 判断是6天或7天
        if($schedule['schedule_week_days'] == 6) {
            array_push($weekDays, '星期六');
        }
        if($schedule['schedule_week_days'] == 7) {
            array_push($weekDays, '星期六');
            array_push($weekDays, '星期日');
        }
        // 星期项列数填充数组
        for($i = 1;$i <= $scheduleDayNum; $i++){
            array_push($weekFillArray, '');
        }
        foreach($weekDays as $weekDay) {
            // 填充数组第一项设置为星期几
            $weekFillArray[0] = $weekDay;
            $data[1] = array_merge($data[1], $weekFillArray);
        }
        // 设置上下午
        $data[2] = array_merge($data[2], $dayFillArray);
        // 设置第四行
        for($i = 1; $i <= $schedule['schedule_week_days']; $i++) {
            foreach($timeArr as $key => $time) {
                array_push($data[3], $time['timeslotInDay']);
                // 从第二行开始
                foreach($classes as $key => $class) {
                    // 从第二行开始
                    $excelIndex = 2 * $key + 4;
                    $data[$excelIndex] = array();
                    // 下一行显示任课老师
                    $data[$excelIndex + 1] = array();
                    array_push($data[$excelIndex], $class['grade_name']);
                    array_push($data[$excelIndex], $class['class_name']);
                    array_push($data[$excelIndex], $class['teacher_name']);
                    array_push($data[$excelIndex + 1], '');
                    array_push($data[$excelIndex + 1], '');
                    array_push($data[$excelIndex + 1], '');

                    // // 暂时不需要导出课程数据，第一列设置默认值
                    // array_push($data[$excelIndex], '体育');
                    // // 下一行显示任课老师
                    // array_push($data[$excelIndex + 1], '张飞');

                    for($j = 1; $j <= $schedule['schedule_week_days']; $j++) {
                        for($k = 1; $k <= $scheduleDayNum; $k++) {
                            $lessonName = '';
                            // 下一行显示任课老师
                            $teacherName = '';
                            foreach($class['lessons'] as $lesson) {
                                if($lesson['schedule_week_index'] == $j && $lesson['schedule_class_index'] == $k) {
                                    // 暂时不需要导出课程数据
                                    $lessonName = $lesson['schedule_lesson'];
                                    $teacherName = $lesson['teacher_name'];
                                }
                            }
                            array_push($data[$excelIndex], $lessonName);
                            // 下一行显示任课老师
                            array_push($data[$excelIndex + 1], $teacherName);
                        }
                    }
                }
            }
        }
        $filename = $this->rmxSchool['school_name'] . '课表模板';
        exportScheduleExcel($filename, $data, $mergeLocations);
    }

    // 导入课表
    public function import() {
        // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
        $onlyOneSchedule = $this->classesModel->check_is_only_one_schedule($this->rmxSchool['id'], $this->campusInfo['id']);
        $CI =& get_instance();
        $CI->load->library('PHPExcel');
        $fileLink = $this->post('fileLink');
        // 暂时只支持xls
        $objReader = \PHPExcel_IOFactory::createReader('Excel5');
        $objReader->setReadDataOnly(true);
        $objPHPExcel = $objReader->load($fileLink);
        $objWorksheet = $objPHPExcel->getActiveSheet();
        $highestRow = $objWorksheet->getHighestRow();
        $highestColumn = $objWorksheet->getHighestColumn();
        $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn);
        $excelData = array();
        for ($row = 1; $row <= $highestRow; $row++) {
            for ($col = 0; $col < $highestColumnIndex; $col++) {
                $excelData[$row][] = (string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
            }
        }
        if(empty($excelData)) {
            throw new Exception('该文件是空文件');
        }
        if($excelData[2][0] !== '年级' || $excelData[2][1] !== '班级' || $excelData[2][2] !== '班主任'){
            throw new Exception('课表格式错误');
        }
        // 批次标题
        $title = $excelData[1][0];
        // 是否有星期五
        $haveFir = false;
        // 是否有星期六
        $haveSat = false;
        // 是否有星期天
        $haveSun = false;
        foreach($excelData[2] as $data) {
            if($data === '星期五') {
                $haveFir = true;
            }
            if($data === '星期六') {
                $haveSat = true;
            }
            if($data === '星期日' || $data === '星期天') {
                $haveSun = true;
            }
        }
        if($haveFir === false) {
            throw new Exception('每周上课天数至少5天,请修改课表');
        }
        if($haveSun === true && $haveSat === false) {
            throw new Exception('不可以有周日数据，而没有周六数据');
        }
        $weekDays = 5;
        if($haveSat) {
            if($haveSun) {
                // 一周上课7天
                $weekDays = 7;
            } else {
                // 一周上课6天
                $weekDays = 6;
            }
        }
        // 上下午
        $morningFirst = 0;
        $morningSecond = 0;
        $afternoonFirst = 0;
        foreach($excelData[3] as $key => $data) {
            if($data === '上午') {
                $morningFirst = $key;
                break;
            }
        }
        foreach($excelData[3] as $key => $data) {
            if($data === '上午') {
                if($key !== $morningFirst) {
                    $morningSecond = $key;
                    break;
                }
            }
        }
        foreach($excelData[3] as $key => $data) {
            if($data === '下午') {
                $afternoonFirst = $key;
                break;
            }
        }
        if($morningFirst === 0 && $afternoonFirst === 0) {
            throw new Exception('上下午数据不能都为空');
        }
        if($morningFirst && $morningSecond && $afternoonFirst) {
            $morningNum = $afternoonFirst - $morningFirst;
            $afternoonNum = $morningSecond - $afternoonFirst;
        } else {
            $monthOneKey = $monthTwoKey = 0;
            foreach($excelData[2] as $key => $data) {
                if($data === '星期一') {
                    $monthOneKey = $key;
                }
                if($data === '星期二') {
                    $monthTwoKey = $key;
                }
            }
            if(empty($monthOneKey)) {
                throw new Exception('星期一不能为空');
            }
            if(empty($monthTwoKey)) {
                throw new Exception('星期二不能为空');
            }
            $lessonNum = $monthTwoKey - $monthOneKey;
            // var_export($lessonNum);exit;
            if($morningFirst == 0) {
                $morningNum = 0;
                $afternoonNum = $lessonNum;
            }
            if($afternoonFirst == 0) {
                $afternoonNum = 0;
                $morningNum = $lessonNum;
            }
        }

        // if($morningNum < 0 || $afternoonNum < 0) {
        //     throw new Exception('上下午项格式有误');
        // }
        if($morningNum < 0) {
            $morningNum = 0;
        }
        if($afternoonNum < 0) {
            $afternoonNum = 0;
        }
        // 时间
        $dayNum = $morningNum + $afternoonNum;
        $timeArr = get_default_schedule_time_arr($dayNum);
        $timeJson = json_encode($timeArr, JSON_UNESCAPED_UNICODE);
        // 获取导入的课程数据
        $lessonExcelArr = array();
        foreach($excelData as $key => $data) {
            if($key <= 4) {
                continue;
            }
            array_push($lessonExcelArr, $data);
        }
        // 获取导入的所有班级
        $classIdArr = array();
        // 获取导入的所有课程
        $lessonDataArr = array();
        // 获取本校全部科目
        $subjectParams['schoolId'] = $this->rmxSchool['id'];
        $subjectParams['isDelete'] = 0;
        $subjectList = $this->schoolModel->get_lesson_list($subjectParams);
        $subjectList = array_value_to_key($subjectList, 'lesson_name');
        // 获取本校全部老师
        $teacherParams['schoolId'] = $this->rmxSchool['id'];
        $teacherParams['isDelete'] = 0;
        $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
        $teacherList = array_value_to_key($teacherList, 'realname');
        foreach($lessonExcelArr as $key => $lessonExcel) {
            // 课程名那列
            if($key % 2 === 0) {
                $className = $lessonExcel[1];
                // 判断班级名是否存在
                $class = $this->classesModel->get_class_info_by_class_name($className, $this->rmxSchool['id']);
                if(empty($class)) {
                    throw new Exception('班级：' . $className . '不存在');
                }
                if($class['class_type'] != CLASSES_TYPE_NORMAL) {
                    throw new Exception('班级：' . $className . '不是行政班');
                }
                // 获取班级id
                $classId = $class['id'];
                if(!in_array($classId, $classIdArr)) {
                    array_push($classIdArr, $classId);
                }
                foreach($lessonExcel as $keyChild => $lessonExcelName) {
                    if($keyChild <= 2) {
                         continue;
                    }
                    if(!empty($lessonExcelName)) {
                        // 判断科目是否存在
                        // $subject = $this->schoolModel->get_lesson_info_by_name($lessonExcelName, $this->rmxSchool['id']);
                        // if(empty($subject)) {
                        //     throw new Exception('科目：' . $lessonExcelName . '不存在');
                        // }
                        if(!isset($subjectList[$lessonExcelName])) {
                            throw new Exception('科目：' . $lessonExcelName . '不存在');
                        }
                        // 获取星期几第几节
                        $weekAndClassIndex = $this->_calculateWeekAndClassIndex($keyChild - 2, $dayNum);
                        // 获取对应的任课老师
                        $teacherName = '';
                        if(isset($lessonExcelArr[$key + 1])) {
                            $teacherName = trim($lessonExcelArr[$key + 1][$keyChild]);
                        }
                        // 判断老师是否存在
                        $teacherId = 0;
                        if(!empty($teacherName)) {
                            // if(!isset($teacherList[$teacherName])) {
                            //     throw new Exception('任课教师：' . $teacherName . '不存在');
                            // }
                            // $teacherId = $teacherList[$teacherName]['id'];
                            // 兼容多个任课老师
                            $nameArr = explode('/', $teacherName);
                            $teacherIdArr = array();
                            foreach($nameArr as $name) {
                                if(trim($name)) {
                                    if(!isset($teacherList[$name])) {
                                        throw new Exception('任课教师：' . $name . '不存在');
                                    }
                                    $teacherIdArr[] = $teacherList[$name]['id'];
                                }
                            }
                            $teacherId = implode(',', $teacherIdArr);
                        }
                        array_push($lessonDataArr, array(
                            'classId' => $classId,
                            'lessonName' => $lessonExcelName,
                            'weekIndex' => $weekAndClassIndex['weekIndex'],
                            'classIndex' => $weekAndClassIndex['classIndex'],
                            'teacherId' => $teacherId
                        ));
                    }
                }
            }
        }
        // 获取学校课程模板
        $scheduleParams['schoolId'] = $this->rmxSchool['id'];
        // 课程暂不区分校区
        $scheduleParams['isThisWeek'] = 1;
        $schedule = $this->classesModel->get_school_schedule_row($scheduleParams);
        $data = array();
        // 导入课程模板
        if(empty($schedule)) {
            // 插入
            $data['school_id'] = $this->rmxSchool['id'];
            $data['campus_id'] = $this->campusInfo['id'];
            $data['schedule_this_week'] = 1;
            $data['schedule_title'] = $title;
            $data['schedule_week_days'] = $weekDays;
            $data['schedule_morning_number'] = $morningNum;
            $data['schedule_afternoon_number'] = $afternoonNum;
            $data['schedule_time_json'] = $timeJson;
            $data['createtime'] = date('Y-m-d H:i:s');
            $data['updatetime'] = date('Y-m-d H:i:s');

            $this->db->insert(ClassesModel::$scheduleTable, $data);
        } else {
            // 多年级作息不判断
            if($onlyOneSchedule) {
                if($schedule['schedule_week_days'] != $weekDays) {
                    throw new Exception('上课天数与现有模板不符，请先修改模板');
                }
                if($schedule['schedule_morning_number'] != $morningNum) {
                    throw new Exception('上午节数与现有模板不符，请先修改模板');
                }
                if($schedule['schedule_afternoon_number'] != $afternoonNum) {
                    throw new Exception('下午节数与现有模板不符，请先修改模板');
                }
            }
        }
        // 先删除导入班级的所有课程
        foreach($classIdArr as $classId) {
            $this->db->update(ClassesModel::$scheduleLessonTable, array(
                'is_delete' => 1,
                'updatetime' => date('Y-m-d H:i:s'),
            ), array(
                'class_id' => $classId,
                'school_id' => $this->rmxSchool['id'],
                'is_delete' => 0
            ));
        }
        // 获取学校课程模板
        $scheduleParams['schoolId'] = $this->rmxSchool['id'];
        // 课程暂不区分校区
        $scheduleParams['isThisWeek'] = 1;
        $scheduleParams['isDelete'] = 0;
        $schedule = $this->classesModel->get_school_schedule_row($scheduleParams);
        // 获取班级列表
        $classParams['isDelete'] = 0;
        $classParams['schoolId'] = $this->rmxSchool['id'];
        $classParams['campusId'] = $this->campusInfo['id'];
        $classList = $this->classesModel->get_class_list($classParams);
        // 使用id作为键
        $classList = array_value_to_key($classList, 'id');
        $insertCount = 0;
        
        // 获取学校所有执教关系任课老师
        $this->load->model('staffModel');
        $coachParams['schoolId'] = $this->rmxSchool['id'];
        $coachParams['campusId'] = $this->campusInfo['id'];
        $coachParams['coachType'] = COACH_TYPE_TEACHER;
        $coachList = $this->staffModel->get_coach_list($coachParams);
        // 使用class_ids,teacher_id,subject_ids作为键
        $coachList = array_value_to_key($coachList, 'class_ids,teacher_id,subject_ids');
        $coachInsertBatch = array();
        $lessonInsertBatch = array();
        $lessonUpdateBatch = array();
        $nowtime = date('Y-m-d H:i:s');
        // 导入课程
        foreach($lessonDataArr as $lessonData) {
            // 判断执教关系是否已存在
            // 兼容多个任课老师
            $lessonTeacherIdArr = explode(',', $lessonData['teacherId']);
            foreach($lessonTeacherIdArr as $lessonTeacherId) {
                $key = $lessonData['classId'] . $lessonTeacherId . $subjectList[$lessonData['lessonName']]['id'];
                $coachTemp = array(
                    'school_id' => $this->rmxSchool['id'],
                    'campus_id' => $this->campusInfo['id'],
                    'teacher_id' => $lessonTeacherId,
                    'class_ids' => $lessonData['classId'],
                    'subject_ids' => $subjectList[$lessonData['lessonName']]['id'],
                    'coach_type' => COACH_TYPE_TEACHER,
                    'is_delete' => 0,
                    'createtime' => $nowtime,
                    'updatetime' => $nowtime
                );
                if(!isset($coachList[$key]) && !in_array($coachTemp, $coachInsertBatch)) {
                    array_push($coachInsertBatch, $coachTemp);
                }
            }

            $lesson = $this->classesModel->get_schedule_lesson_info_for_import($schedule['id'], $lessonData['weekIndex'], $lessonData['classIndex'], $lessonData['classId']);
            // 将班级课室设置为课程课室
            $roomId = isset($classList[$lessonData['classId']]) ? $classList[$lessonData['classId']]['classroom_id'] : 0;
            if(empty($lesson)) {
                // 插入课程
                // $this->db->insert(ClassesModel::$scheduleLessonTable, array(
                //     'school_id' => $this->rmxSchool['id'],
                //     'campus_id' => $this->campusInfo['id'],
                //     'class_id' => $lessonData['classId'],
                //     'schedule_id' => $schedule['id'],
                //     'schedule_week_index' => $lessonData['weekIndex'],
                //     'schedule_class_index' => $lessonData['classIndex'],
                //     'schedule_lesson' => $lessonData['lessonName'],
                //     'schedule_teacher' => $lessonData['teacherId'],
                //     'schedule_room_id' => $roomId,
                //     'is_delete' => 0,
                //     'createtime' => date('Y-m-d H:i:s'),
                //     'updatetime' => date('Y-m-d H:i:s')
                // ));
                // $insertCount ++;

                array_push($lessonInsertBatch, array(
                    'school_id' => $this->rmxSchool['id'],
                    'campus_id' => $this->campusInfo['id'],
                    'class_id' => $lessonData['classId'],
                    'schedule_id' => $schedule['id'],
                    'schedule_week_index' => $lessonData['weekIndex'],
                    'schedule_class_index' => $lessonData['classIndex'],
                    'schedule_lesson' => $lessonData['lessonName'],
                    'schedule_teacher' => $lessonData['teacherId'],
                    'schedule_room_id' => $roomId,
                    'is_delete' => 0,
                    'createtime' => date('Y-m-d H:i:s'),
                    'updatetime' => date('Y-m-d H:i:s')
                ));
            } else {
                // 更新课程
                // $this->db->where('id', $lesson['id']);
                // $this->db->update(ClassesModel::$scheduleLessonTable, array(
                //     'is_delete' => 0,
                //     'updatetime' => date('Y-m-d H:i:s'),
                //     'schedule_lesson' => $lessonData['lessonName'],
                //     'schedule_teacher' => $lessonData['teacherId'],
                //     'schedule_room_id' => $roomId
                // ));

                array_push($lessonUpdateBatch, array(
                    'id' => $lesson['id'],
                    'is_delete' => 0,
                    'updatetime' => date('Y-m-d H:i:s'),
                    'schedule_lesson' => $lessonData['lessonName'],
                    'schedule_teacher' => $lessonData['teacherId'],
                    'schedule_room_id' => $roomId
                ));
            }
        }
        if($coachInsertBatch) {
            // 插入执教关系
            $this->db->insert_batch(StaffModel::$coachTable, $coachInsertBatch);
        }
        if($lessonInsertBatch) {
            // 插入执教关系
            $this->db->insert_batch(ClassesModel::$scheduleLessonTable, $lessonInsertBatch);
        }
        if($lessonUpdateBatch) {
            // 插入执教关系
            $this->db->update_batch(ClassesModel::$scheduleLessonTable, $lessonUpdateBatch, 'id');
        }

        // 插入日志
        $this->load->library('logger');
        $actionType = $this->logger->get_action_type('import');
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' => '导入课表，插入了'. count($lessonInsertBatch). '条数据'
        ));
        // 多年级作息设置对应的schedule_id
        if(!$onlyOneSchedule) {
            // 年级不同作息
            $gradeScheduleParams['schoolId'] = $this->rmxSchool['id'];
            $gradeScheduleParams['campusId'] = $this->campusInfo['id'];
            $gradeScheduleParams['isDelete'] = 0;
            $gradeScheduleList = $this->classesModel->get_school_schedule($gradeScheduleParams);
            $gradeScheduleList = array_value_to_key($gradeScheduleList, 'grade_id');
            // 获取全校课程
            $lessonParams['schoolId'] = $this->rmxSchool['id'];
            $lessons = $this->classesModel->get_school_schedule_lesson($lessonParams);
            $lessonUpdateBatch = array();
            foreach($lessons as $lesson) {
                $classId = $lesson['class_id'];
                if(isset($classList[$classId])) {
                    $gradeId = $classList[$classId]['grade_id'];
                    if(isset($gradeScheduleList[$gradeId])) {
                        if($gradeScheduleList[$gradeId]['id'] != $lesson['schedule_id']) {
                            array_push($lessonUpdateBatch, array(
                                'id' => $lesson['id'],
                                'schedule_id' => $gradeScheduleList[$gradeId]['id']
                            ));
                        }
                    }
                }
            }
            // echo'<pre>';var_export($lessonUpdateBatch);exit;
            if($lessonUpdateBatch) {
                // 插入执教关系
                $this->db->update_batch(ClassesModel::$scheduleLessonTable, $lessonUpdateBatch, 'id');
            }
        }

        exit(json('导入成功，插入了' . count($lessonInsertBatch) . '条数据', true));
    }

    // 导出课表
    public function export_teaching(){
        $this->load->model('staffModel');
        $onlyOneSchedule = $this->classesModel->check_is_only_one_schedule($this->rmxSchool['id'], $this->campusInfo['id']);
        if($onlyOneSchedule) {
            // 获取学校课程模板
            $scheduleParams['schoolId'] = $this->rmxSchool['id'];
            // 课程暂不区分校区
            $scheduleParams['isThisWeek'] = 1;
            $scheduleParams['isDelete'] = 0;
            $schedule = $this->classesModel->get_school_schedule_row($scheduleParams);
        } else {
            // 年级不同作息
            $gradeScheduleParams['schoolId'] = $this->rmxSchool['id'];
            $gradeScheduleParams['campusId'] = $this->campusInfo['id'];
            $gradeScheduleParams['isDelete'] = 0;
            $gradeScheduleList = $this->classesModel->get_school_schedule($gradeScheduleParams);
            $maxGradeSchedule = array();
            if(empty($gradeScheduleList)) {
                throw new Exception('找不到该学校课程模板');
            }
            foreach($gradeScheduleList as $key => $gradeSchedule) {
                // 获取天数最大值，节数最大值
                if($key == 0) {
                    $maxGradeSchedule = $gradeSchedule;
                } else {
                    $timeArr = json_decode($gradeSchedule['schedule_time_json'], true);
                    $maxGradeScheduleTimeArr = json_decode($maxGradeSchedule['schedule_time_json'], true);
                    $maxGradeScheduleCount = count($maxGradeScheduleTimeArr);
                    if($maxGradeScheduleCount < count($timeArr)) {
                        $maxGradeSchedule = $gradeSchedule;
                    }
                }
            }
            $schedule = $maxGradeSchedule;
        }
        if(empty($schedule)) {
            throw new Exception('找不到该学校课程模板');
        }
        // 课程节数
        $timeArr = json_decode($schedule['schedule_time_json'], true);
        if(empty($timeArr)) {
            throw new Exception('找不到课程模板的上课时间');
        }
        $data = array();
        $classParams['schoolId'] = $this->rmxSchool['id'];
        $classParams['campusId'] = $this->campusInfo['id'];
        // 行政班
        $classParams['classType'] = CLASSES_TYPE_TEACHING;
        $classParams['isDelete'] = 0;
        // 按年级排序
        $classParams['orderBy'] = '`grade_id` ASC, `id` ASC';
        $classes = $this->classesModel->get_class_list($classParams);

        foreach($classes as $key => $class) {
            // 获取年级名称
            $classes[$key]['grade_name'] = '';
            $grade = $this->classesModel->get_grade_info($class['grade_id']);
            if($grade) {
                $classes[$key]['grade_name'] = $grade['grade_name'];
            }
            // 获取班主任
            $classes[$key]['teacher_name'] = '';
            // $teacher = $this->schoolModel->get_school_user_info_realname($class['class_master']);
            $masterCoach = $this->staffModel->get_master_coach_by_class($class['id']);
            if($masterCoach) {
                $teacher = $this->schoolModel->get_school_user_info_realname($masterCoach['teacher_id']);
            } else {
                $teacher = NULL;
            }

            if($teacher) {
                $classes[$key]['teacher_name'] = $teacher['realname'] ? $teacher['realname'] : $teacher['username'];
            }
            // 获取班级课程
            $classes[$key]['lessons'] = array();
            $lessonParams['schoolId'] = $this->rmxSchool['id'];
            $lessonParams['classId'] = $class['id'];
            // $lessonParams['scheduleId'] = $schedule['id'];  // 兼容年级不同作息
            $lessons = $this->classesModel->get_school_schedule_lesson($lessonParams);
            foreach($lessons as $keyLesson => $lesson) {
                 //获取任课老师
                 $lessons[$keyLesson]['teacher_name'] = '';
                 $teacher = $this->schoolModel->get_school_user_info_realname($lesson['schedule_teacher']);
                 // 兼容多任课老师
                 $teacherIdArr = explode(',', $lesson['schedule_teacher']);
                 $teacherNameArr = array();
                 if($teacherIdArr) {
                     foreach($teacherIdArr as $teacherId) {
                         $teacher = $this->schoolModel->get_school_user_info_realname($teacherId);
                         if($teacher) {
                             $teacherNameArr[] = $teacher['realname'];
                         }
                     }
                 }
                 $lessons[$keyLesson]['teacher_name'] = $teacherNameArr ? implode('/', $teacherNameArr) : '';
                 // 获取上课地点
                 $classroom = $this->classesModel->get_classroom_info($lesson['schedule_room_id']);
                 $classroomName = '';
                 if($classroom) {
                    $classroomName = $classroom['classroom_name'];
                 }
                 $lessons[$keyLesson]['classroom_name'] =  $classroomName;
            }
            if($lessons) {
                $classes[$key]['lessons'] = $lessons;
            }
        }
        // 合并单元位置
        $mergeLocations = array();
		// excel坐标
        $excelSheetArr = excelSheetIndex();
        // 一天课程数
        $scheduleDayNum = $schedule['schedule_morning_number'] + $schedule['schedule_afternoon_number'];
        // 星期项起始横坐标是2
        $weekRowEnd = 2;
        // 星期项起点坐标是D2
        $weekIndexBegin = 'D2:';
        // 星期项列数填充数组
        $weekFillArray = array();
        // 上下午起始横坐标是2
        $dayRowEnd = 2;
        // 上下午起点坐标是D3
        $dayIndexBegin = 'D3:';
        // 上下午列数填充数组
        $dayFillArray = array();
        for($i = 1; $i <= $schedule['schedule_week_days']; $i++) {
            // 合并星期项
            $weekRowEnd = $weekRowEnd + $scheduleDayNum;
            $mergeLocations[] = $weekIndexBegin . $excelSheetArr[$weekRowEnd] . 2;
            // 下一个起点坐标
            $weekIndexBegin = $excelSheetArr[$weekRowEnd + 1] . '2:';
            
            // 判断是否有下午课程
            if($schedule['schedule_morning_number'] > 0) {
                // 合并上午项
                $dayRowEnd = $dayRowEnd + $schedule['schedule_morning_number'];
                $mergeLocations[] = $dayIndexBegin . $excelSheetArr[$dayRowEnd] . 3;
                // 上下午列数填充数组
                array_push($dayFillArray, '上午');
                for($j = 1; $j <= $schedule['schedule_morning_number'] - 1; $j++) {
                    array_push($dayFillArray, '');
                }
                // 下一个起点坐标
                $dayIndexBegin = $excelSheetArr[$dayRowEnd + 1] . '3:';
            }

            // 判断是否有下午课程
            if($schedule['schedule_afternoon_number'] > 0) {
                // 合并下午项
                $dayRowEnd = $dayRowEnd + $schedule['schedule_afternoon_number'];
                $mergeLocations[] = $dayIndexBegin . $excelSheetArr[$dayRowEnd] . 3;
                // 上下午列数填充数组
                array_push($dayFillArray, '下午');
                for($j = 1; $j <= $schedule['schedule_afternoon_number'] - 1; $j++) {
                    array_push($dayFillArray, '');
                }
                // 下一个起点坐标
                $dayIndexBegin = $excelSheetArr[$dayRowEnd + 1] . '3:';
            }
        }
        // 合并年级
        $arr = array();
        if(!empty($classes)) {
            foreach($classes as $class) {
                $gradeId = $class['grade_id'];
                if(isset($arr[$gradeId])) {
                    $arr[$gradeId]++;
                } else {
                    $arr[$gradeId] = 1;
                }
            }
            $begin = 5;
            foreach($arr as $val) {
                // $end = $begin + intval($val) * 2 - 1;
                $end = $begin + intval($val) * 3 - 1;
                array_push($mergeLocations, 'A' . $begin . ':A' . $end);
                $begin = $end + 1;
            }
        }
        $firstRow = $schedule['schedule_title'] ? $schedule['schedule_title'] : $this->rmxSchool['school_name'] . '总课表';
        $data[0] = array($firstRow);
        $data[1] = array('年级', '班级', '班主任');
        $data[2] = array('年级', '班级', '班主任');
        $data[3] = array('年级', '班级', '班主任');
        // 设置星期项
        $weekDays = array('星期一', '星期二', '星期三', '星期四', '星期五');
        // 判断是6天或7天
        if($schedule['schedule_week_days'] == 6) {
            array_push($weekDays, '星期六');
        }
        if($schedule['schedule_week_days'] == 7) {
            array_push($weekDays, '星期六');
            array_push($weekDays, '星期日');
        }
        // 星期项列数填充数组
        for($i = 1;$i <= $scheduleDayNum; $i++){
            array_push($weekFillArray, '');
        }
        foreach($weekDays as $weekDay) {
            // 填充数组第一项设置为星期几
            $weekFillArray[0] = $weekDay;
            $data[1] = array_merge($data[1], $weekFillArray);
        }
        // 设置上下午
        $data[2] = array_merge($data[2], $dayFillArray);
        // 设置第四行
        for($i = 1; $i <= $schedule['schedule_week_days']; $i++) {
            foreach($timeArr as $key => $time) {
                array_push($data[3], $time['timeslotInDay']);
                // 从第二行开始
                foreach($classes as $key => $class) {
                    // 从第二行开始
                    // $excelIndex = 2 * $key + 4;
                    $excelIndex = 3 * $key + 4;
                    $data[$excelIndex] = array();
                    // 下一行显示任课老师
                    $data[$excelIndex + 1] = array();

                    // 下一行显示课室
                    $data[$excelIndex + 2] = array();

                    array_push($data[$excelIndex], $class['grade_name']);
                    array_push($data[$excelIndex], $class['class_name']);
                    array_push($data[$excelIndex], $class['teacher_name']);

                    array_push($data[$excelIndex + 1], '');
                    array_push($data[$excelIndex + 1], '');
                    array_push($data[$excelIndex + 1], '');


                    array_push($data[$excelIndex + 2], '');
                    array_push($data[$excelIndex + 2], '');
                    array_push($data[$excelIndex + 2], '');

                    // // 暂时不需要导出课程数据，第一列设置默认值
                    // array_push($data[$excelIndex], '体育');
                    // // 下一行显示任课老师
                    // array_push($data[$excelIndex + 1], '张飞');
                    // // 下一行显示上课课室
                    // array_push($data[$excelIndex + 2], 'A101');

                    for($j = 1; $j <= $schedule['schedule_week_days']; $j++) {
                        for($k = 1; $k <= $scheduleDayNum; $k++) {
                            $lessonName = '';
                            // 下一行显示任课老师
                            $teacherName = '';
                            // 下一行显示上课课室
                            $classroomName = '';
                            foreach($class['lessons'] as $lesson) {
                                if($lesson['schedule_week_index'] == $j && $lesson['schedule_class_index'] == $k) {
                                    // 暂时不需要导出课程数据
                                    $lessonName = $lesson['schedule_lesson'];
                                    $teacherName = $lesson['teacher_name'];
                                    $classroomName = $lesson['classroom_name'];
                                }
                            }
                            array_push($data[$excelIndex], $lessonName);
                            // 下一行显示任课老师
                            array_push($data[$excelIndex + 1], $teacherName);
                            // 下一行显示上课课室
                            array_push($data[$excelIndex + 2], $classroomName);
                        }
                    }
                }
            }
        }
        // echo '<pre>';var_export($mergeLocations);exit;
        $filename = $this->rmxSchool['school_name'] . '走班课表模板';
        exportScheduleExcel($filename, $data, $mergeLocations);
    }

    // 导入课表
    public function import_teaching() {
        // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
        $onlyOneSchedule = $this->classesModel->check_is_only_one_schedule($this->rmxSchool['id'], $this->campusInfo['id']);
        $CI =& get_instance();
        $CI->load->library('PHPExcel');
        $fileLink = $this->post('fileLink');
        // 暂时只支持xls
        $objReader = \PHPExcel_IOFactory::createReader('Excel5');
        $objReader->setReadDataOnly(true);
        $objPHPExcel = $objReader->load($fileLink);
        $objWorksheet = $objPHPExcel->getActiveSheet();
        $highestRow = $objWorksheet->getHighestRow();
        $highestColumn = $objWorksheet->getHighestColumn();
        $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn);
        $excelData = array();
        for ($row = 1; $row <= $highestRow; $row++) {
            for ($col = 0; $col < $highestColumnIndex; $col++) {
                $excelData[$row][] = (string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
            }
        }
        if(empty($excelData)) {
            throw new Exception('该文件是空文件');
        }
        if($excelData[2][0] !== '年级' || $excelData[2][1] !== '班级' || $excelData[2][2] !== '班主任'){
            throw new Exception('课表格式错误');
        }
        // 批次标题
        $title = $excelData[1][0];
        // 是否有星期五
        $haveFir = false;
        // 是否有星期六
        $haveSat = false;
        // 是否有星期天
        $haveSun = false;
        foreach($excelData[2] as $data) {
            if($data === '星期五') {
                $haveFir = true;
            }
            if($data === '星期六') {
                $haveSat = true;
            }
            if($data === '星期日' || $data === '星期天') {
                $haveSun = true;
            }
        }
        if($haveFir === false) {
            throw new Exception('每周上课天数至少5天,请修改课表');
        }
        if($haveSun === true && $haveSat === false) {
            throw new Exception('不可以有周日数据，而没有周六数据');
        }
        $weekDays = 5;
        if($haveSat) {
            if($haveSun) {
                // 一周上课7天
                $weekDays = 7;
            } else {
                // 一周上课6天
                $weekDays = 6;
            }
        }
        // 上下午
        $morningFirst = 0;
        $morningSecond = 0;
        $afternoonFirst = 0;
        foreach($excelData[3] as $key => $data) {
            if($data === '上午') {
                $morningFirst = $key;
                break;
            }
        }
        foreach($excelData[3] as $key => $data) {
            if($data === '上午') {
                if($key !== $morningFirst) {
                    $morningSecond = $key;
                    break;
                }
            }
        }
        foreach($excelData[3] as $key => $data) {
            if($data === '下午') {
                $afternoonFirst = $key;
                break;
            }
        }
        if($morningFirst === 0 && $afternoonFirst === 0) {
            throw new Exception('上下午数据不能都为空');
        }
        if($morningFirst && $morningSecond && $afternoonFirst) {
            $morningNum = $afternoonFirst - $morningFirst;
            $afternoonNum = $morningSecond - $afternoonFirst;
        } else {
            $monthOneKey = $monthTwoKey = 0;
            foreach($excelData[2] as $key => $data) {
                if($data === '星期一') {
                    $monthOneKey = $key;
                }
                if($data === '星期二') {
                    $monthTwoKey = $key;
                }
            }
            if(empty($monthOneKey)) {
                throw new Exception('星期一不能为空');
            }
            if(empty($monthTwoKey)) {
                throw new Exception('星期二不能为空');
            }
            $lessonNum = $monthTwoKey - $monthOneKey;
            // var_export($lessonNum);exit;
            if($morningFirst == 0) {
                $morningNum = 0;
                $afternoonNum = $lessonNum;
            }
            if($afternoonFirst == 0) {
                $afternoonNum = 0;
                $morningNum = $lessonNum;
            }
        }

        // if($morningNum < 0 || $afternoonNum < 0) {
        //     throw new Exception('上下午项格式有误');
        // }
        if($morningNum < 0) {
            $morningNum = 0;
        }
        if($afternoonNum < 0) {
            $afternoonNum = 0;
        }
        // 时间
        $dayNum = $morningNum + $afternoonNum;
        $timeArr = get_default_schedule_time_arr($dayNum);
        $timeJson = json_encode($timeArr, JSON_UNESCAPED_UNICODE);
        // 获取导入的课程数据
        $lessonExcelArr = array();
        foreach($excelData as $key => $data) {
            if($key <= 4) {
                continue;
            }
            array_push($lessonExcelArr, $data);
        }
        // 获取导入的所有班级
        $classIdArr = array();
        // 获取导入的所有课程
        $lessonDataArr = array();
        // 获取本校全部科目
        $subjectParams['schoolId'] = $this->rmxSchool['id'];
        $subjectParams['isDelete'] = 0;
        $subjectList = $this->schoolModel->get_lesson_list($subjectParams);
        $subjectList = array_value_to_key($subjectList, 'lesson_name');
        // 获取本校全部老师
        $teacherParams['schoolId'] = $this->rmxSchool['id'];
        $teacherParams['isDelete'] = 0;
        $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
        $teacherList = array_value_to_key($teacherList, 'realname');
        // 获取本校全部课室
        $roomParams['schoolId'] = $this->rmxSchool['id'];
        $roomParams['isDelete'] = 0;
        $classroomList = $this->classesModel->get_classroom_list($roomParams);
        $classroomList = array_value_to_key($classroomList, 'classroom_name');
        // echo '<pre>';var_export($lessonExcelArr);exit;
        foreach($lessonExcelArr as $key => $lessonExcel) {
            // 课程名那列（走班）
            if($key % 3 === 0) {
                $className = $lessonExcel[1];
                // 判断班级名是否存在
                $class = $this->classesModel->get_class_info_by_class_name($className, $this->rmxSchool['id']);
                if(empty($class)) {
                    throw new Exception('班级：' . $className . '不存在');
                }
                if($class['class_type'] != CLASSES_TYPE_TEACHING) {
                    throw new Exception('班级：' . $className . '不是教学班');
                }
                // 获取班级id
                $classId = $class['id'];
                if(!in_array($classId, $classIdArr)) {
                    array_push($classIdArr, $classId);
                }
                foreach($lessonExcel as $keyChild => $lessonExcelName) {
                    if($keyChild <= 2) {
                         continue;
                    }
                    if(!empty($lessonExcelName)) {
                        if(!isset($subjectList[$lessonExcelName])) {
                            throw new Exception('科目：' . $lessonExcelName . '不存在');
                        }
                        // 获取星期几第几节
                        $weekAndClassIndex = $this->_calculateWeekAndClassIndex($keyChild - 2, $dayNum);
                        // 获取对应的任课老师
                        $teacherName = '';
                        if(isset($lessonExcelArr[$key + 1])) {
                            $teacherName = trim($lessonExcelArr[$key + 1][$keyChild]);
                        }
                        // 判断老师是否存在
                        // $teacherId = 0;
                        // if(!empty($teacherName)) {
                        //     if(!isset($teacherList[$teacherName])) {
                        //         throw new Exception('任课教师：' . $teacherName . '不存在');
                        //     }
                        //     $teacherId = $teacherList[$teacherName]['id'];
                        // }
                        // 兼容多个任课老师
                        $nameArr = explode('/', $teacherName);
                        $teacherIdArr = array();
                        foreach($nameArr as $name) {
                            if(trim($name)) {
                                if(!isset($teacherList[$name])) {
                                    throw new Exception('任课教师：' . $name . '不存在');
                                }
                                $teacherIdArr[] = $teacherList[$name]['id'];
                            }
                        }
                        $teacherId = implode(',', $teacherIdArr);

                        // 获取上课课室
                        $scheduleRoomName = '';
                        if(isset($lessonExcelArr[$key + 2])) {
                            $scheduleRoomName = trim($lessonExcelArr[$key + 2][$keyChild]);
                        }
                        if(empty($scheduleRoomName)) {
                            throw new Exception('上课课室不能为空');
                        }
                        // 判断课室是否存在
                        $roomId = 0;
                        if(!empty($scheduleRoomName)) {
                            if(!isset($classroomList[$scheduleRoomName])) {
                                throw new Exception('上课课室：' . $scheduleRoomName . '不存在');
                            }
                            $roomId = $classroomList[$scheduleRoomName]['id'];
                        }

                        array_push($lessonDataArr, array(
                            'classId' => $classId,
                            'lessonName' => $lessonExcelName,
                            'weekIndex' => $weekAndClassIndex['weekIndex'],
                            'classIndex' => $weekAndClassIndex['classIndex'],
                            'teacherId' => $teacherId,
                            'scheduleRoomId' => $roomId
                        ));
                    }
                }
            }
        }
        // 获取学校课程模板
        $scheduleParams['schoolId'] = $this->rmxSchool['id'];
        // 课程暂不区分校区
        $scheduleParams['isThisWeek'] = 1;
        $schedule = $this->classesModel->get_school_schedule_row($scheduleParams);
        $data = array();
        // 导入课程模板
        if(empty($schedule)) {
            // 插入
            $data['school_id'] = $this->rmxSchool['id'];
            $data['campus_id'] = $this->campusInfo['id'];
            $data['schedule_this_week'] = 1;
            $data['schedule_title'] = $title;
            $data['schedule_week_days'] = $weekDays;
            $data['schedule_morning_number'] = $morningNum;
            $data['schedule_afternoon_number'] = $afternoonNum;
            $data['schedule_time_json'] = $timeJson;
            $data['createtime'] = date('Y-m-d H:i:s');
            $data['updatetime'] = date('Y-m-d H:i:s');

            $this->db->insert(ClassesModel::$scheduleTable, $data);
        } else {

            if($onlyOneSchedule) {
                if($schedule['schedule_week_days'] != $weekDays) {
                    throw new Exception('上课天数与现有模板不符，请先修改模板');
                }
                if($schedule['schedule_morning_number'] != $morningNum) {
                    throw new Exception('上午节数与现有模板不符，请先修改模板');
                }
                if($schedule['schedule_afternoon_number'] != $afternoonNum) {
                    throw new Exception('下午节数与现有模板不符，请先修改模板');
                }
            }
        }
        // 先删除导入班级的所有课程
        foreach($classIdArr as $classId) {
            $this->db->update(ClassesModel::$scheduleLessonTable, array(
                'is_delete' => 1,
                'updatetime' => date('Y-m-d H:i:s'),
            ), array(
                'class_id' => $classId,
                'school_id' => $this->rmxSchool['id'],
                'is_delete' => 0
            ));
        }
        // 获取学校课程模板
        $scheduleParams['schoolId'] = $this->rmxSchool['id'];
        // 课程暂不区分校区
        $scheduleParams['isThisWeek'] = 1;
        $schedule = $this->classesModel->get_school_schedule_row($scheduleParams);
        // 获取班级列表
        $classParams['isDelete'] = 0;
        $classParams['schoolId'] = $this->rmxSchool['id'];
        $classParams['campusId'] = $this->campusInfo['id'];
        $classList = $this->classesModel->get_class_list($classParams);
        // 使用id作为键
        $classList = array_value_to_key($classList, 'id');
        $insertCount = 0;
        
        // 获取学校所有执教关系任课老师
        $this->load->model('staffModel');
        $coachParams['schoolId'] = $this->rmxSchool['id'];
        $coachParams['campusId'] = $this->campusInfo['id'];
        $coachParams['coachType'] = COACH_TYPE_TEACHER;
        $coachList = $this->staffModel->get_coach_list($coachParams);
        // 使用class_ids,teacher_id,subject_ids作为键
        $coachList = array_value_to_key($coachList, 'class_ids,teacher_id,subject_ids');
        $coachInsertBatch = array();
        $lessonInsertBatch = array();
        $lessonUpdateBatch = array();
        $nowtime = date('Y-m-d H:i:s');
        // 导入课程
        foreach($lessonDataArr as $lessonData) {
            // 判断执教关系是否已存在
            // 兼容多个任课老师
            $lessonTeacherIdArr = explode(',', $lessonData['teacherId']);
            foreach($lessonTeacherIdArr as $lessonTeacherId) {
                $key = $lessonData['classId'] . $lessonTeacherId . $subjectList[$lessonData['lessonName']]['id'];
                $coachTemp = array(
                    'school_id' => $this->rmxSchool['id'],
                    'campus_id' => $this->campusInfo['id'],
                    'teacher_id' => $lessonTeacherId,
                    'class_ids' => $lessonData['classId'],
                    'subject_ids' => $subjectList[$lessonData['lessonName']]['id'],
                    'coach_type' => COACH_TYPE_TEACHER,
                    'is_delete' => 0,
                    'createtime' => $nowtime,
                    'updatetime' => $nowtime
                );
                if(!isset($coachList[$key]) && !in_array($coachTemp, $coachInsertBatch)) {
                    array_push($coachInsertBatch, $coachTemp);
                }
            }

            $lesson = $this->classesModel->get_schedule_lesson_info_for_import($schedule['id'], $lessonData['weekIndex'], $lessonData['classIndex'], $lessonData['classId']);
            // // 将班级课室设置为课程课室
            // $roomId = isset($classList[$lessonData['classId']]) ? $classList[$lessonData['classId']]['classroom_id'] : 0;
            if(empty($lesson)) {
                array_push($lessonInsertBatch, array(
                    'school_id' => $this->rmxSchool['id'],
                    'campus_id' => $this->campusInfo['id'],
                    'class_id' => $lessonData['classId'],
                    'schedule_id' => $schedule['id'],
                    'schedule_week_index' => $lessonData['weekIndex'],
                    'schedule_class_index' => $lessonData['classIndex'],
                    'schedule_lesson' => $lessonData['lessonName'],
                    'schedule_teacher' => $lessonData['teacherId'],
                    'schedule_room_id' => $lessonData['scheduleRoomId'], // 走班
                    'is_delete' => 0,
                    'createtime' => date('Y-m-d H:i:s'),
                    'updatetime' => date('Y-m-d H:i:s')
                ));
            } else {
                // 更新课程
                array_push($lessonUpdateBatch, array(
                    'id' => $lesson['id'],
                    'is_delete' => 0,
                    'updatetime' => date('Y-m-d H:i:s'),
                    'schedule_lesson' => $lessonData['lessonName'],
                    'schedule_teacher' => $lessonData['teacherId'],
                    'schedule_room_id' => $lessonData['scheduleRoomId'] // 走班
                ));
            }
        }
        if($coachInsertBatch) {
            // 插入执教关系
            $this->db->insert_batch(StaffModel::$coachTable, $coachInsertBatch);
        }
        if($lessonInsertBatch) {
            // 插入执教关系
            $this->db->insert_batch(ClassesModel::$scheduleLessonTable, $lessonInsertBatch);
        }
        if($lessonUpdateBatch) {
            // 插入执教关系
            $this->db->update_batch(ClassesModel::$scheduleLessonTable, $lessonUpdateBatch, 'id');
        }

        // 插入日志
        $this->load->library('logger');
        $actionType = $this->logger->get_action_type('import');
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' => '导入走班课表，插入了'. count($lessonInsertBatch). '条数据'
        ));
        // 多年级作息设置对应的schedule_id
        if(!$onlyOneSchedule) {
            // 年级不同作息
            $gradeScheduleParams['schoolId'] = $this->rmxSchool['id'];
            $gradeScheduleParams['campusId'] = $this->campusInfo['id'];
            $gradeScheduleParams['isDelete'] = 0;
            $gradeScheduleList = $this->classesModel->get_school_schedule($gradeScheduleParams);
            $gradeScheduleList = array_value_to_key($gradeScheduleList, 'grade_id');
            // 获取全校课程
            $lessonParams['schoolId'] = $this->rmxSchool['id'];
            $lessons = $this->classesModel->get_school_schedule_lesson($lessonParams);
            $lessonUpdateBatch = array();
            foreach($lessons as $lesson) {
                $classId = $lesson['class_id'];
                if(isset($classList[$classId])) {
                    $gradeId = $classList[$classId]['grade_id'];
                    if(isset($gradeScheduleList[$gradeId])) {
                        if($gradeScheduleList[$gradeId]['id'] != $lesson['schedule_id']) {
                            array_push($lessonUpdateBatch, array(
                                'id' => $lesson['id'],
                                'schedule_id' => $gradeScheduleList[$gradeId]['id']
                            ));
                        }
                    }
                }
            }
            // echo'<pre>';var_export($lessonUpdateBatch);exit;
            if($lessonUpdateBatch) {
                // 插入执教关系
                $this->db->update_batch(ClassesModel::$scheduleLessonTable, $lessonUpdateBatch, 'id');
            }
}
        exit(json('导入成功，插入了' . count($lessonInsertBatch) . '条数据', true));
    }

    // 计算星期几第几节
    private function _calculateWeekAndClassIndex($index, $dayNum) {
        $weekIndex = ceil($index / $dayNum);
        $classIndex = $index % $dayNum;
        if($classIndex === 0) {
            $classIndex = $dayNum;
        }
        return array(
            'weekIndex' => $weekIndex,
            'classIndex' => $classIndex
        );
    }
}